<template>
  <rx-fit style="padding-top: 8px;">
    <div slot="toolheader" foldbtn="false" border="false">
      <div class="table-operator" style="padding: 0;">
        <a-button @click="addRow" size="small">
          {{$ti18('rxList.add','新增')}}
        </a-button>
        <a-tooltip placement="bottomLeft">
                    <span slot="title">
                        {{i18n("msa.pmtTip","保存成功后，还需前往右侧的【权限配置】设置才生效")}}
                    </span>
          <a-icon type="question-circle-o"/>
        </a-tooltip>
      </div>
    </div>
    <rx-grid ref="table"
             :dataSource="pmtFields"
             :columns="pmtColumns"
             id-field="id"
             :allowRowSelect="false"
             :showPage="false"
             :bordered="true"
             :showExpandedRowRender="true"
             :expanRowKeys="expanRowKeys"
             @rowExpand="rowExpand"
    >
            <span slot="name" slot-scope="{text,record,index}">
                <a-input v-model="record.name" />
            </span>
      <span slot="action" slot-scope="{ text, record,index }" class="actionIcons">
                <span @click.stop="removeRow(record,index)">{{$ti18('rxList.delBtn','删除')}}</span>
            </span>
      <template slot="expandedRowRender" slot-scope="{record,index}">
        <rx-fit style="padding-top: 8px;height: 350px ;width: calc(100% - 20px);margin-left: 10px" >
          <div slot="toolheader" foldbtn="false" border="false">
            <div class="table-operator">
              <a-button size="small" @click="addAndGrantRow">{{i18n('list.addAndGrantRow','新增条件分组')}}</a-button>
              <a-button size="small" @click="upRow">{{i18n('list.upRow','上移')}}</a-button>
              <a-button size="small" @click="downRow">{{i18n('list.downRow','下移')}}</a-button>
              <a-dropdown>
                <a-menu slot="overlay"  >
                  <a-menu-item @click="insertPermission(item)"
                               :key="item.click"
                               v-for="item in clickEventAry"> {{item.title}} </a-menu-item>
                </a-menu>
                <a-button size="small"> {{i18n('list.addDataPermiss','添加数据权限')}} <a-icon type="down" /> </a-button>
              </a-dropdown>
              <a-button size="small" @click="removeGrantRow">{{i18n('list.delPermiss','删除权限')}}</a-button>
            </div>
          </div>
          <rx-grid :ref="'table_list_'+record.id" :dataSource="grantListFields[index]"
                   :columns="grantColumns" :allowRowSelect="true" :multiSelect="true" :showPage="false"
                   :bordered="true">
                    <span slot="type" slot-scope="{text,record,index}">
                      <a-select v-model="record.type" v-if="record.isGroup==true">
                        <a-select-option value="conditionAnd">{{i18n('options.conditionAnd','按AND分组')}}</a-select-option>
                        <a-select-option value="conditionOr">{{i18n('options.conditionOr','按OR分组')}}</a-select-option>
                      </a-select>
                      <template v-else>
                        {{record.type_name}}
                      </template>
                    </span>
            <span slot="tablePre" slot-scope="{text,record,index}" v-if="record.type!='conditionAnd' && record.type!='conditionOr'">
                      <a-input v-model="record.tablePre" />
                    </span>
            <span slot="desc" slot-scope="{text,record,index}" v-if="record.type!='conditionAnd' && record.type!='conditionOr'">
                      <a-input v-model="record.desc" />
                    </span>
            <span slot="field" slot-scope="{text,record,index}" v-if="record.type!='conditionAnd' && record.type!='conditionOr'">
                        <template v-if="record.type=='field'">
                            <a-input v-model="record.field" style="width:calc( 100% -  25px  ) "></a-input>
                            <rx-popover :comboBox="{'width':'200px'}">
                                <span slot="title"><a-icon type="search" style="margin-left: 4px"/></span>
                                <div slot="content" slot-scope="{ close }">
                                    <a-select
                                        style="width: 100%;"
                                        v-model="record.field"
                                        :options="fieldDatas"
                                        @change="changeFieldName($event,record)"
                                        :getPopupContainer="p=>p.parentNode"
                                        :dropdown-menu-style="{width:'300px'}"
                                        :dropdownMatchSelectWidth="false"
                                    >
                                    </a-select>
                                </div>
                            </rx-popover>
                        </template>
                      <a-select v-else v-model="record.field" @change="changeFieldName($event,record)" :options="fieldDatas"></a-select>
                    </span>
            <span slot="op" slot-scope="{text,record,index}" v-if="record.type!='conditionAnd' && record.type!='conditionOr' && record.type!='logicDel'">
                      <a-select v-model="record.op" @change="opChange($event,record)">
                        <a-select-option value="=">{{i18n('options.equal','等于')}}</a-select-option>
                        <a-select-option value="in">{{i18n('options.range','范围')}}</a-select-option>
                      </a-select>
                    </span>
            <span slot="scope" slot-scope="{text,record,index}" v-if="record.type!='conditionAnd' && record.type!='conditionOr'">
                      <a-select v-if="record.type=='user' && record.op=='='" v-model="record.scope">
                        <a-select-option value="SELF">{{i18n('options.oneself','自己')}}</a-select-option>
                        <a-select-option value="DUP_USERS">{{i18n('options.dupUsers','直接上级用户')}}</a-select-option>
                        <a-select-option value="UP_USERS">{{i18n('options.upUsers','所有上级用户')}}</a-select-option>
                        <a-select-option value="DDOWN_USERS">{{i18n('options.ddownUsers','直属下级用户')}}</a-select-option>
                        <a-select-option value="DOWN_USERS">{{i18n('options.downUsers','所有下级用户')}}</a-select-option>
                      </a-select>
                      <a-select v-if="record.type=='group' && record.op=='='" v-model="record.scope">
                        <a-select-option value="SELF_DEP">{{i18n('options.selfDep','当前部门')}}</a-select-option>
                        <a-select-option value="SELF_DOWN">{{i18n('options.selfDown','当前人部门(下级)')}}</a-select-option>
                        <a-select-option value="DUP_DEPS">{{i18n('options.dupDeps','直接上级部门')}}</a-select-option>
                        <a-select-option value="UP_DEPS">{{i18n('options.upDeps','所有上级部门')}}</a-select-option>
                        <a-select-option value="DDOWN_DEPS">{{i18n('options.ddownDeps','本部门及下级部门')}}</a-select-option>
                        <a-select-option value="DOWN_DEPS">{{i18n('options.downDeps','所有下级部门')}}</a-select-option>
                      </a-select>
                      <a-select v-if="record.type=='company'" v-model="record.scope">
                        <a-select-option value="CURRENT">{{i18n('options.currentBranch','当前分公司')}}</a-select-option>
                        <a-select-option value="DDOWN">{{i18n('options.subCompany','下级公司')}}</a-select-option>
                      </a-select>
                    <a-select @change="clearScope2(record)" v-if="record.type=='field' && record.op=='=' && (record.dataType==null || record.dataType=='string' || record.dataType=='varchar' || record.dataType=='clob')" :defaultValue="text" v-model="record.scope" style="width: 100%">
                      <a-select-option value="fixedVar" :key="index">固定值</a-select-option>
                      <a-select-option value="script" :key="index">脚本</a-select-option>
                      <a-select-option value="constantVar" :key="index">常量</a-select-option>
                    </a-select>
                      <a-input-number v-model="record.scope" v-if="record.type=='field' && (record.dataType=='int' || record.dataType=='number')" />
                      <a-date-picker v-model="record.scope" valueFormat="YYYY-MM-DD" v-if="record.type=='field' && record.dataType=='date'" />
                      <rx-input-button v-model="record.scope"  :showType="true" :multiValue="false"
                                       @click="selUserData($event,record)" v-if="record.type=='user' && record.op=='in'" style="background:#fff;"/>
                      <rx-input-button v-model="record.scope" :single="false"
                                       :multiValue="false" @click="selGroupData($event,record)" v-if="record.type=='group' && record.op=='in'" />
                      <rx-input-button v-model="record.scope" :single="true" @click="rangSetDlg($event,record)" v-show="record.type=='field' && record.op=='in' && (record.dataType==null || record.dataType=='string' || record.dataType=='varchar' || record.dataType=='clob')"  />
                    </span>

            <span slot="scope2" slot-scope="{text,record,index}" v-if="record.type!='conditionAnd' && record.type!='conditionOr'">
                      <a-input-number v-model="record.scope2" v-if="record.type=='field' && record.op=='in' && (record.dataType=='int' || record.dataType=='number')" />
                      <a-date-picker v-model="record.scope2" valueFormat="YYYY-MM-DD" v-if="record.type=='field' && record.op=='in' && record.dataType=='date'" />
                      <a-select  mode="tags" v-model="record.scope2" :options="getSelectData(record)" v-if="record.scope=='selfData' && record.type=='field' && record.op=='in' && (record.dataType==null || record.dataType=='string' || record.dataType=='varchar' || record.dataType=='clob')" />
                      <rx-select :multiSelect="true" v-model="record.scope2" :dataSource="sqlData" data-field="data" :valueField="record.configs.valueField" :textField="record.configs.textField" v-if="record.scope=='sql' && record.type=='field' && record.op=='in' && (record.dataType==null || record.dataType=='string' || record.dataType=='varchar' || record.dataType=='clob')" />
                      <rx-select :multiSelect="true" v-model="record.scope2" :dataSource="dicData" value-field="value" text-field="name" v-if="record.scope=='dic' && record.type=='field' && record.op=='in' && (record.dataType==null || record.dataType=='string' || record.dataType=='varchar' || record.dataType=='clob')" />
                      <rx-select :multiSelect="false" v-model="record.scope2" :dataSource="userRelsData" value-field="key" text-field="name" v-if="!['SELF','CHARGE_DEPT_USERS'].includes(record.scope) && record.type=='user'" />
                      <rx-input-button v-model="record.scope2" :single="false" :multiValue="true" @click="showDialog($event,record)" v-if="record.scope=='dialog' && record.type=='field' && record.op=='in' && (record.dataType==null || record.dataType=='string' || record.dataType=='varchar' || record.dataType=='clob')" />

                    <a-input v-if="record.type=='field' && record.op=='=' && record.scope=='fixedVar'" :defaultValue="text" v-model="record.scope2"/>
                    <a-input-group v-if="record.type=='field' && record.op=='=' && record.scope=='script'" compact>
                    <a-button @click="openScriptQuery(record)">...</a-button>
                    </a-input-group>
                    <a-select v-if="record.type=='field' && record.op=='=' && record.scope=='constantVar'" :defaultValue="text" :options="constantField"
                              v-model="record.scope2" style="width: 100%">
                    </a-select>

                    </span>
          </rx-grid>
        </rx-fit>
      </template>
    </rx-grid>
  </rx-fit>
</template>

<script>
import {Util,Dialog} from "@lowcode/jpaas-common-lib";
import DialogBox from "@/assets/js/DialogBox";
import FormCustomQueryApi from "@/api/form/core/formCustomQuery";
import FormBoDatasApi from "@/api/form/core/formBoDatas";
export default {
  name: "FormBoListEditDataConf",
  props:["fieldDatas","boListId"],
  data(){
    return {
      expanRowKeys: [],
      pmtFields: [],
      pmtColumns: [
        {title: this.$ti18('rxForm.name','名称'), dataIndex: 'name',  scopedSlots: {customRender: 'name'}},
        {title: this.$ti18('rxList.action','操作'), dataIndex: 'action', scopedSlots: {customRender: 'action'}}
      ],
      grantListFields:[],
      grantColumns: [{title: this.i18n('form.permissionType','权限类型'), dataIndex: 'type',scopedSlots: {customRender: 'type'}},
        {title: this.i18n('form.permissionDesc','权限描述'), dataIndex: 'desc',  scopedSlots: {customRender: 'desc'}},
        {title: this.i18n('form.tablePrefix','表前缀'), dataIndex: 'tablePre',  scopedSlots: {customRender: 'tablePre'}, width:120},
        {
          title: this.i18n('form.filterField','筛选字段'),
          dataIndex: 'field',
          scopedSlots: {customRender: 'field'},
          width: 180,
          customCell:(record,rowIndex)=>{if(record){ return {class:'noOverflow'}}}
        },
        {
          title: this.i18n('form.comparator','比较符'),
          dataIndex: 'op',
          scopedSlots: {customRender: 'op'}
        },
        {
          title: this.i18n('form.scope1','作用域1'),
          dataIndex: 'scope',
          scopedSlots: {customRender: 'scope'}
        },
        {
          title: this.i18n('form.scope2','作用域2'),
          dataIndex: 'scope2',
          scopedSlots: {customRender: 'scope2'}
        }],
      clickEventAry:[{
        title: this.i18n('grantRow.addFieldPermiss','新增字段权限'),
        click:"addDataFieldGrantRow",
      },{
        title:this.i18n('grantRow.addUserPermiss','新增用户权限'),
        click:"addDataUserGrantRow",
      },{
        title:this.i18n('grantRow.addGroupPermiss','新增组权限'),
        click:"addDataGroupGrantRow",
      },{
        title:this.i18n('grantRow.addCreatorPermiss','新增创建人权限'),
        click:"addDataCreateUserGrantRow",
      },{
        title:this.i18n('grantRow.addCreateDeptPermiss','新增创建部门权限'),
        click:"addDataCreateGroupGrantRow",
      },{
        title:this.i18n('grantRow.addCompanyPermiss','新增公司权限'),
        click:"addCompanyGrantRow",
      },{
        title:this.i18n('grantRow.addLogicDelPermiss','新增逻辑删除权限'),
        click:"addDataCreateLogicDelGrantRow",
      }
      ],
      constantField:[],
      sqlData:[],
      dicData:[],
      userRelsData:[]
    }
  },
  created() {
    this.loadConstants();
    this.initDatas();
  },
  methods:{
    i18n(name,text,key){
      return this.$ti18(name,text,"FormBoPmt",key);
    },
    insertPermission(item){
      let fn=this[item.click];
      fn();
    },
    loadConstants() {
      FormCustomQueryApi.getConstants().then(data => {
        this.constantField = this.constantField.concat(data.map(item => {
          return {label: item.val, value: item.key}
        }));
      })
    },
    openScriptQuery(record) {
      let script = record.scope2;
      Dialog.openScripttextDialog({
        curVm: this, widthHeight: ['800px', '600px'], data: {script: script}
      }, function (self, data) {
        record.scope2 = data;
      })
    },
    clearScope2(record){
      record.scope2 = "";
    },
    async initDatas() {
      if (!this.boListId) {
        return;
      }
      var self = this;
      let res = await FormBoDatasApi.getList(this.boListId);
      if (!res.success) {
        return;
      }
      let list = res.data;
      self.pmtFields = list;
      for (var i = 0; i < this.pmtFields.length; i++) {
        this.grantListFields[i] = JSON.parse(this.pmtFields[i].setting || "[]");
      }
    },
    getData(){
      var arr=[];
      var data=this.$refs.table.getData();

      for(var i=0;i<data.length;i++){
        let obj=data[i];
        if(!obj.name){
          this.$refs.table.removeRows([obj.id]);
          continue;
        }
        if(this.$refs["table_list_"+obj.id]) {
          obj.setting = this.$refs["table_list_" + obj.id].getData();
        }
        //如果存在数据权限，并内容为空时，禁止保存
        if (obj.setting==null || obj.setting.length==0){
          this.$message.error(this.i18n('msa.isNullNoSave',"数据权限为空，无法保存"))
          return;
        }
        arr.push(obj);
      }
      return arr;
    },
    rowExpand(expanded,record){
      if(expanded){
        this.expanRowKeys=[record.id];
      }
    },
    addRow(){
      var id=Util.randomId();
      this.$refs.table.addRow({id:id});
      this.expanRowKeys=[id];
      this.grantListFields.push([]);
    },
    removeRow(record,index) {
      this.grantListFields.splice(index,1);
      this.$refs.table.removeRows([record.id]);
    },
    removeGrantRow(){
      var table=this.$refs["table_list_"+this.expanRowKeys[0]];
      table.removeSelected();
      table.$forceUpdate();
    },
    addAndGrantRow(){
      this.addTreeRow({typeExt:{key:'conditionAnd',label:'按AND分组'},type: 'conditionAnd', type_name: '按AND分组',isGroup:true})
    },
    //数据权限表格方法
    addDataFieldGrantRow() {
      this.addTreeRow({fieldExt:'',opExt:'',scopeExt:'',type: 'field', type_name: this.i18n('grantRow.filterField','按字段过滤'),op:'=',op_name:'等于'})
    },
    addDataUserGrantRow() {
      this.addTreeRow({fieldExt:'',opExt:'',scopeExt:'',type: 'user', type_name: this.i18n('grantRow.filterUser','按用户过滤'),op:'=',op_name:'等于',scope:'SELF'})
    },
    addDataGroupGrantRow() {
      this.addTreeRow({fieldExt:'',opExt:'',scopeExt:'',type: 'group', type_name: this.i18n('grantRow.filterUserGroup','按用户组过滤'),op:'=',op_name:'等于',scope:'SELF_DEP'})
    },
    addDataInstGrantRow() {
      this.addTreeRow({fieldExt:'',opExt:'',scopeExt:'',type: 'inst', type_name: this.i18n('grantRow.filterOrg','按机构过滤'),op:'=',op_name:'等于'})
    },
    addDataCreateUserGrantRow() {
      this.addTreeRow({fieldExt:'',opExt:'',scopeExt:'',type: 'user', type_name: this.i18n('grantRow.filterUser','按用户过滤'), field: 'CREATE_BY_', field_name: '创建人ID',op:'=',op_name:'等于',scope:'SELF'})
    },
    addDataCreateGroupGrantRow() {
      this.addTreeRow({fieldExt:'',opExt:'',scopeExt:'',type: 'group', type_name: this.i18n('grantRow.filterUserGroup','按用户组过滤'), field: 'CREATE_DEP_ID_', field_name: '组ID',op:'=',op_name:'等于',scope:'SELF_DEP'})
    },
    addCompanyGrantRow(){
      this.addTreeRow({fieldExt:'',opExt:'',scopeExt:'',type: 'company', type_name: this.i18n('grantRow.filterCompany','按公司过滤'), field: 'COMPANY_ID_', field_name: '公司ID',op:'=',op_name:'等于',scope:'CURRENT'})
    },
    addDataCreateInstGrantRow() {
      this.addTreeRow({fieldExt:'',opExt:'',scopeExt:'',type: 'inst', type_name: this.i18n('grantRow.filterOrg','按机构过滤'), field: 'TENANT_ID_', field_name: '租户ID',op:'=',op_name:'等于'})
    },
    addDataCreateLogicDelGrantRow() {
      this.addTreeRow({fieldExt:'',opExt:'',scopeExt:'',type: 'logicDel', type_name: this.i18n('grantRow.filterLogicDel','按逻辑删除过滤'), field: 'DELETED_', field_name: '逻辑删除',op:'=',op_name:'等于'})
    },
    addGrantRow(row) {
      this.$refs["table_list_"+this.expanRowKeys[0]].addRow(row);
    },
    addTreeRow(row){
      var table=this.$refs["table_list_"+this.expanRowKeys[0]];
      var selRow=table.getSelectedRow();
      if(!selRow){
        this.addGrantRow(row);
        return;
      }
      if(selRow.type!='conditionAnd' && selRow.type!='conditionOr'){
        this.$message.error(this.i18n('msa.addTreeTips','只能加在条件分组下面！'));
        return;
      }
      if(!selRow.children){
        selRow.children=[];
      }
      row[table.parentField]=selRow[table.idField];
      table.addItem(selRow.children,row);
      table.$forceUpdate();
    },
    opChange(e,record){
      record.scope = "";
      if(record.type=="user" || record.type=="group"){
        record.scope = "";
      }
    },
    getUserData(data,type){
      let obj = new Function('return ' + data )();
      if(obj && obj.value){
        let value = obj.value.split(',');
        let text = obj.text.split(',');
        return value.map((item,index)=>{
          return type=='user'? {userId:item,fullName:text[index]} : {groupId:item,name:text[index]}
        })
      }
      return []
    },
    selUserData(vm,record){
      let inputSelf = vm ;
      let data = this.getUserData(record.scope,'user') ;
      Dialog.openUserDialog({
        curVm: this, data: {single: false,data:data}, widthHeight: ['900px', '600px']
      },  (self, data) =>{
        var ids=[];
        var names=[];
        for(var i=0;i<data.length;i++){
          ids.push(data[i].userId);
          names.push(data[i].fullName);
        }
        let obj = JSON.stringify({
          value:ids.join(','),
          text:names.join(',')
        })
        record.scope = obj ;
        inputSelf.setVaules(obj);
      })
    },
    selGroupData(vm,record){
      let inputSelf = vm ;
      let data = this.getUserData(record.scope,'group') ;
      let _obj = {
        key:"0",
        name:this.$comi18('form.haveSelectGroup', '上次已选择的用户组'),
        data:data
      }
      Dialog.openGroupDialog({
        curVm: this, data: {single: false,initGroups:[_obj]}, widthHeight: ['900px', '600px']
      }, function (self, data) {
        var ids=[];
        var names=[];
        for(var i=0;i<data.length;i++){
          ids.push(data[i].groupId);
          names.push(data[i].name);
        }
        let _obj = JSON.stringify({text:names.join(','),value:ids.join(',')});
        record.scope = _obj ;
        inputSelf.setVaules(_obj);
      })
    },
    rangSetDlg(vm,record){
      var config = {curVm: this, widthHeight: ['800px', '600px'],
        data:{scope:record['scope'],scope_name:record['scope_name'],configs:record['configs']}};
      var self = this;
      DialogBox.openFieldRangConfig(config,function(data){
        record['configs']=data.configs;
        vm.setVal(data.scope);
        if (record.scope=='sql'){
            self.getQueryForJson(record)
        }else if (record.scope=='dic'){
            self.getDicData(record)
        }else if(!['SELF','CHARGE_DEPT_USERS'].includes(record.scope)){
            self.getUserRelsData()
        }
      })
    },
    getSelectData(record){
        if (record.configs.selDatas){
            return JSON.parse(record.configs.selDatas);
        }
    },
      /**
       * 获取自定义sql数据
       */
    async getQueryForJson(record){
        let result=await FormCustomQueryApi.doQuery(record.configs.sql)
        this.sqlData=result
    },
      /**
       * 获取字典数据
       */
      async getDicData(record){
        let result=await FormCustomQueryApi.getByAlias(record)
        this.dicData=result
    },
      async getUserRelsData(){
          let result=await FormCustomQueryApi.getUserRels()
          this.userRelsData=result
      },
    showDialog(vm,record){
      DialogBox.dialog({key:record.configs.dialog},{
        curVm: vm
      },function(action,data){
        var rows=data.rows || data;
        var labels=[];
        var values=[];
        for(var i=0;i<rows.length;i++){
          labels.push(rows[i][record.configs.textField]);
          values.push(rows[i][record.configs.valueField]);
        }
        vm.setVal(values.join(','),labels.join(','));
      });
    },
    upRow() {
      this.$refs["table_list_"+this.expanRowKeys[0]].moveUp();
    },
    downRow() {
      this.$refs["table_list_"+this.expanRowKeys[0]].moveDown();
    },
    changeFieldName(value,record){
      for(var i=0;i<this.fieldDatas.length;i++){
        if(this.fieldDatas[i].value==value){
          record.dataType=this.fieldDatas[i].key;
          break;
        }
      }
    }
  }
}
</script>

<style scoped>

</style>